﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace TFile.CAD.Repositorios
{
    public class XMLDataRepositorio
    {
        public void InsertData(string descricao, string arquivo)
        {
            FileStream fs = new FileStream(@"Documentos.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(fs);
            XmlElement newcatalogentry = xmldoc.CreateElement("Documento");
            XmlAttribute newcatalogattr = xmldoc.CreateAttribute("ID");
            newcatalogattr.Value = Guid.NewGuid().ToString();
            newcatalogentry.SetAttributeNode(newcatalogattr);
            XmlElement firstelement = xmldoc.CreateElement("Data");
            firstelement.InnerText = DateTime.Now.ToShortDateString();
            newcatalogentry.AppendChild(firstelement);
            XmlElement secondelement = xmldoc.CreateElement("Descricao");
            secondelement.InnerText = descricao;
            newcatalogentry.AppendChild(secondelement);
            XmlElement thirdelement = xmldoc.CreateElement("Arquivo");
            thirdelement.InnerText = arquivo.ToUpper();
            newcatalogentry.AppendChild(thirdelement);
            xmldoc.DocumentElement.InsertAfter(newcatalogentry, xmldoc.DocumentElement.LastChild);
            xmldoc.Save(fs);
            fs.Close();
        }

        public void DeleteData(string iddoc)
        {
            FileStream fs = new FileStream(@"Documentos.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(fs);
            XmlNode xmlnode = xmldoc.SelectSingleNode("/Documentos/Documento[@ID='" + iddoc + "']");
            xmlnode.ParentNode.RemoveChild(xmlnode);
            xmldoc.Save(fs);
            fs.Close(); 
        }
    }
}
